<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta content="telephone=no,email=no" name="format-detection">
    <!--防止css、js资源缓存-->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <script type="text/javascript" src="asserts/resource/js/flexible_C.js" ></script>
    <title>历史轨迹</title>
    <link rel="stylesheet" href="asserts/resource/css/common.css">
    <link rel="stylesheet" href="asserts/resource/css/css.css">
    <style type="text/css">
        body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
        #map_canvas{width:100%;height:100%;}
        #result {width:100%;}
    </style>
    <script src="http://api.map.baidu.com/api?v=3.0&ak=A4LmXLHVeMzGbVYqMvC4i5tiodzwqKn5"></script>
    <script type="text/javascript" src="asserts/resource/js/jquery.min.js"></script>
    <script type="text/javascript" src="asserts/resource/layer/mobile/layer.js"></script>
    <script type="text/javascript" src="asserts/resource/js/js.js"></script>
</head>
<body id="historicalmap">
    <div id="map_canvas"></div>
    <div id="result"></div>
    <div class="runhistory">
        <div class="runH">
            <div class="runAndstop" id="run">
                <span data-run='1' data-init='true' id="begin">开始</span>
            </div>
            <div class="barWrap">
                <div class="grade_warp">
                    <div class="User_ratings User_grade">
                        <div class="ratings_bars">
                            <span class="bars_10">速度</span>
                            <div id="wrapper1">
                                <!--填充块-->
                                <div id="fill1" wid='0'></div>
                                <!--滑块-->
                                <div id="slider1"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="grade_warp">
                    <div class="User_ratings User_grade">
                        <div class="ratings_bars">
                            <span class="bars_10">进度</span>
                            <div id="wrapper2">
                                <!--填充块-->
                                <div id="fill2"></div>
                                <!--滑块-->
                                <div id="slider2"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">

	var parameterData = JSON.parse(localStorage.dateJson);
	//时间条件
	var startTime=parameterData.startTime;
	var endTime=parameterData.endTime;
	var lbsStatus=parameterData.lbsStatus;

	//轨迹点数组
    var mark=[];
    var markerArr = [];
	//每个轨迹点信息数组
   var arrPoisInfo=[];

   // var mark = [new BMap.Point(106.497965, 29.629306), new BMap.Point(106.498217, 29.629326), new BMap.Point(106.498455, 29.629326), new BMap.Point(106.498522, 29.629322), new BMap.Point(106.498634, 29.629063), new BMap.Point(106.498702, 29.628741), new BMap.Point(106.498733, 29.628592), new BMap.Point(106.498733, 29.628466)];


    function getData() {
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            async: false, // 使用同步方式
            dataType: "json",//预期服务器返回的数据类型
            url: "/position/history" ,//url
            data: {"startTime":startTime,"endTime":endTime,"locationType":lbsStatus},
            success: function (result) {
				var data= result.data;
                if (result.status == 1) {
                   $.each(data,function(index,value){
                       sContent='';
                       mark.push(new BMap.Point(value.longitudeShow,value.latitudeShow));
					  // var dumpEnergy=value.batteryInfo==null?'-':value.batteryInfo;
                       sContent = '<lable class="infoWindow"><ul class ="markwrap">'
                           // +'<p class="Dclose"><a id="Dclose">x</a></p>'
                           +'<li><span>昵称：</span>' + value.terminalName + '</li>'
                           +'<li><span >定位方式：</span>' + value.locationType + '</li>'
                           if(value.locationType=="lbs"){
                        	   if(value.dumpEnergy){
                               	sContent+='<li><span>当前电量：</span>' +value.dumpEnergy +'%'+ '</li>';
                        	   }
                           }
                       sContent+='<li>' + value.recordTime + '</li></ul></lable>';
                       arrPoisInfo.push(sContent);
                       // arrPoisInfo.push({lng:value.longitudeShow,lat:value.latitudeShow,html:sContent,pauseTime:1});
                    });
                }else{
                    layerMsg(result.msg,2);
                }
            },
            error : function() {
                layerMsg('网络异常!',2);
            }
        });
    }
    //获取轨迹数据
    getData();
    var map = new BMap.Map('map_canvas');
    // map.centerAndZoom(arrPois[0],19);
    // map.setViewport(arrPois);

    $.extend({
        myData:{speed: 2000, action: 'start'},  // 数据
        seI_autoFn: null,   // 定时器
        autoFnIndex:0,      // 定时器执行的次数
        autoFn:function (action) {    // start/stop/pause
            var action  = action || $.myData.action;

            if ( $.seI_autoFn ) clearTimeout($.seI_autoFn);

            if ( 'stop' === action ) {          // 停止计时
                $.autoFnIndex = 0;
                $.myData.action = 'start';

                $.myData.run.firstElementChild.removeAttribute('run');
                $.myData.run.firstElementChild.innerText = '开始';
            } else if ( 'pause' === action ) {  // 暂停计时
                $.myData.action = action;
            } else if ( 'start' === action ) {  // 开始计时
                if ($.autoFnIndex < $.myData.markerArr.length) {
                    $.myData.markerArr[Math.round($.autoFnIndex)].click();
                    $.autoFnIndex++;
                } else {
                    action = 'stop';    // 执行完一轮，强制停止
                    $.myData.run.firstElementChild.innerText = '停止';
                    map.panTo(mark[0], 17);
                    $('.infoWindow').remove();
                }
                $.seI_autoFn = setTimeout(function() { $.autoFn(action) }, $.myData.speed);
            }
        }
    });
    $(function() {

        map.enableScrollWheelZoom(true);
        // map.disableDragging();     //禁止拖拽,but双点依然可以移动地图

        // 编写自定义函数,创建标注
        function addMarker(point, option){
            var marker = new BMap.Marker(point, option);
            var point;

            map.addOverlay(marker);

            map.addEventListener("tilesloaded",function(){
                var index = 0;
                point = marker.point;
                 $(marker.V).off('click').on("click", function(e){//自动执行点击事件，并作用在run上

                    var $tar = $(event.target);

                    $('.infoWindow').remove();

                    $tar.append(arrPoisInfo[option]);

                    $(".infoWindow").css(
                            {"left":- parseInt($(".infoWindow").width()/2 - 5),"top":- parseInt($(".infoWindow").height() + 15)}
                        );

                    index = 'BMap_Marker BMap_noprint' === e.target.className ? $tar.index() : -1;
                    slide(index);

                    map.panTo(point,18);
                });

                if ( markerArr.length >= mark.length ) return;
                markerArr[markerArr.length] = marker.V;
                $.myData.markerArr = markerArr;

            });
        }


        $.myData.count = mark.length;   // 总执行次数
        $.myData.run  = document.getElementById('run');

        // map.centerAndZoom(mark[0], 19);
        map.setViewport(mark);

        for (var i = 0, len = mark.length; i < len; i++) {
            addMarker(mark[i], i);
        }

        // 进度条
        $('#wrapper1, #fill1, #wrapper2, #fill2').on('click', function(e) {
            e.stopPropagation();
            var target = e.target;
            var wrap;
            var btn;
            var fill;
            var objX = null;
            var flag = false;
            var flagSpeed = false;
            var flagProgress = false;
            var ratio = 1;
            var makerindex = markerArr.length-1;

            if ( 'wrapper1' === target.id || 'fill1' === target.id ) {  // 速度
                wrap = document.getElementById('wrapper1'); // 获取滑层元素
                btn = document.getElementById('slider1');   // 获取滑块元素
                fill = document.getElementById('fill1');    // 获取背景填充元素
                flag = flagSpeed = true;
            } else if ( 'wrapper2' === target.id || 'fill2' === target.id ) {   // 进度
                wrap = document.getElementById('wrapper2'); // 获取滑层元素
                btn = document.getElementById('slider2');   // 获取滑块元素
                fill = document.getElementById('fill2');    // 获取背景填充元素
                flag = flagProgress = true;
            }
            if ( flag ) {
                objX = ranging(wrap, btn, e, e.type);
                ratio = objX.relX/objX.totalX;              // 获得当前滑动点的比率
                if ( flagProgress ) {
                    $.autoFnIndex = Math.round(ratio*makerindex);
                    markerArr[$.autoFnIndex].click()
                };
                move(btn, fill, objX.relX);
                if ( !flagProgress ) getSpeed();
            }
        });

        $('#slider1, #slider2').on('touchstart touchmove touchend', function(e) {
            var target = e.target;
            var wrap;
            var btn;
            var fill;
            var objX = null;
            var touchObj1 = event.touches[0];   // 单点触控
            var flag = false;
            var flagSpeed = false;
            var flagProgress = false;
            var ratio = 1;
            var makerindex = markerArr.length-1;

            if ( 'touchstart' === e.type ) {    // 避免点击相同点进行的滑块宽度的变距
                return false;
            } else if ( 'touchmove' === e.type ) {
                if ( 'slider1' === target.id ) {    // 速度
                    wrap = document.getElementById('wrapper1'); // 获取滑层元素
                    btn = document.getElementById('slider1');   // 获取滑块元素
                    fill = document.getElementById('fill1');    // 获取背景填充元素
                    flag = flagSpeed = true;
                } else if ( 'slider2' === target.id ) { // 进度
                    wrap = document.getElementById('wrapper2'); // 获取滑层元素
                    btn = document.getElementById('slider2');   // 获取滑块元素
                    fill = document.getElementById('fill2');    // 获取背景填充元素
                    flag = flagProgress = true;
                }
                if ( flag ) {
                    objX = ranging(wrap, btn, e, e.type, touchObj1);
                    ratio = objX.relX/objX.totalX;  // 获得当前滑动点的比率
                    if ( flagProgress ) {
                        $.autoFnIndex = Math.round(ratio*makerindex);
                        markerArr[$.autoFnIndex].click()
                    };
                    move(btn, fill, objX.relX);     // 动起来
                    if ( !flagProgress ) getSpeed();
                }
            } else if ( 'touchend' === e.type ) {

            }
        });

        /**
         * 计算实际滑动距离
         * @param  wrap  滑层元素
         * @param  btn   滑块元素
         * @param  e     event
         * @param  type  触发事件名称
         * @param  touch 触动对象
         * @return       实际滑动距离
         */
        function ranging(wrap, btn, e, type, touch) {
            var w = parseFloat(window.getComputedStyle(wrap,null).width);   // 获取滑动框的宽度
            var parX = $(wrap).offset().left;   // 获取当前元素距离文档左边界的距离
            var borderW = parseFloat($(wrap).css('borderWidth'));           //  获取边框宽度
            var btnW = parseFloat(window.getComputedStyle(btn,null).width); //  滑块的宽度
            var relX = 0;                       // 实际计算点击时的水平值;

            'click' === type ? (relX = e.pageX - parX - btnW) : (relX = touch.pageX - parX - btnW);

            if ( relX > w-2*borderW-btnW ) {
                relX = w-2*borderW-btnW;
            } else if ( relX < borderW ) {
                relX = 0;
            }

            return {relX: relX, totalX: w-2*borderW-btnW};
        };

        /**
         * 滑块滑动的视觉效果
         * @param  btn  滑块元素
         * @param  fill 填充元素
         * @param  relX 实际滑动距离
         * @param  percent 是否使用百分比为单位
         * @return      undefined
         */
        function move(btn, fill, relX, percent) {
            relX += percent ? '%' : 'px';

            $(btn).css({
                'left': relX
            });
            $(fill).css({
                'width': relX
            }).attr('wid', relX);
        };

        /**
         * 点击marker后进度滑条自动跟进
         * @param stage 第几个marker被点击
         * @return      undefined
         */
        function slide(stage) {
            var wrap = document.getElementById('wrapper2'); // 获取滑层元素
            var btn = document.getElementById('slider2');   // 获取滑块元素
            var fill = document.getElementById('fill2');    // 获取背景填充元素
            var wrapWidth = parseFloat(window.getComputedStyle(wrap,null).width);
            var btnWidth = parseFloat(window.getComputedStyle(btn,null).width);
            var wrapBorder = parseFloat($(wrap).css('borderWidth'));

            move(btn, fill, Math.ceil((stage+1)*100/markerArr.length)/100*(wrapWidth-btnWidth-2*wrapBorder));
        };

        // 获取速度
        function getSpeed(speed) {
            if ( !Number(speed) ) speed = 2000; // 默认速度
            var speed = speed || 2000;
            var wrapper1 = document.getElementById('wrapper1');
            var fill1 = document.getElementById('fill1');
            var slider1 = document.getElementById('slider1');
            var s = speed - speed*(parseFloat($(fill1).attr('wid')) / (parseFloat(window.getComputedStyle(wrapper1,null).width) -
                2 * parseFloat(window.getComputedStyle(wrapper1,null).borderWidth) -
                parseFloat(window.getComputedStyle(slider1,null).width)));
            // return $.myData.speed = s < 400 ? 400 : s; // 最小速度不能小于400ms
            return $.myData.speed = s;
        };

        $('#run').on('click', function() {
            if ( $(this).attr('run') ) return;
            var text = $(this).find('span').text();

            if ( '开始' === text ) {          // 开始
                $(this).find('span').text('暂停').attr('run', true);
                getSpeed();
                $.autoFn('start');
            } else if ( '暂停' === text ) {   // 暂停
                $(this).find('span').text('开始').removeAttr('run');
                $.autoFn('pasue');
            }
        });

    });


    //  //路书上面点图标
   //  var icon= new BMap.Icon("asserts/resource/img/imei.png", new BMap.Size(15,30));
   //  var marker=new BMap.Marker(arrPois[0],{
   //        icon : icon
   // });
   //
	// map.addOverlay(marker);
   //
   //  BMapLib.LuShu.prototype._move=function(initPos,targetPos,effect) {
   //      var pointsArr=[initPos,targetPos];  //点数组
   //      var me = this,
   //          //当前的帧数
   //          currentCount = 0,
   //          //步长，米/秒
   //          timer = 10,
   //          step = this._opts.speed / (10000 / timer),
   //          //初始坐标
   //          init_pos = this._projection.lngLatToPoint(initPos),
   //          //获取结束点的(x,y)坐标
   //          target_pos = this._projection.lngLatToPoint(targetPos),
   //          //总的步长
   //          count = Math.round(me._getDistance(init_pos, target_pos) / step);
   //      //显示折线 syj201607191107
   //      this._map.addOverlay(new BMap.Polyline(pointsArr, {
   //          strokeColor : "#789cfc",
   //          strokeWeight : 5,
   //          strokeOpacity : 0.5
   //      })); // 画线
   //      //如果小于1直接移动到下一点
   //      if (count < 1) {
   //          me._moveNext(++me.i);
   //          return;
   //      }
   //      me._intervalFlag = setInterval(function() {
   //          //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
   //          if (currentCount >= count) {
   //              clearInterval(me._intervalFlag);
   //              //移动的点已经超过总的长度
   //              if(me.i > me._path.length){
   //                  return;
   //              }
   //              //运行下一个点
   //              me._moveNext(++me.i);
   //          }else {
   //              currentCount++;
   //              var x = effect(init_pos.x, target_pos.x, currentCount, count),
   //                  y = effect(init_pos.y, target_pos.y, currentCount, count),
   //                  pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
   //              //设置marker
   //              if(currentCount == 1){
   //                  var proPos = null;
   //                  if(me.i - 1 >= 0){
   //                      proPos = me._path[me.i - 1];
   //                  }
   //                  if(me._opts.enableRotation == true){
   //                      me.setRotation(proPos,initPos,targetPos);
   //                  }
   //                  if(me._opts.autoView){
   //                      if(!me._map.getBounds().containsPoint(pos)){
   //                          me._map.setCenter(pos);
   //                      }
   //                  }
   //              }
   //              //正在移动
   //              me._marker.setPosition(pos);
   //              //设置自定义overlay的位置
   //              me._setInfoWin(pos);
   //          }
   //      },timer);
   //  };
	// 	var lushu = new BMapLib.LuShu(map, arrPois, {
   //          //landmarkPois:此参数是路书移动的时候碰到这个点会触发pauseTime停留中设置的时间，单位为秒，经纬度误差超过十米不会停止
   //          landmarkPois:arrPoisInfo,
   //          enableRotation:true,
   //          defaultContent: '终端移动中...',
   //          speed: 500,//速度，单位米每秒
   //          icon:icon,
   //          autoView: false,
   //          enableRotation: false
   //      });
   //      setTimeout(function(){
   //          $(".HMapLabel").parent().css("background","rgba(0,0,0,0)");
   //          },300)
 	// var run = document.getElementById("run");
   //  run.onclick = function(){
	//     var ChangeK = this.childNodes[1];
	//     var runS = ChangeK.getAttribute("data-run");
	//     if(runS == 1){
	//     	ChangeK.innerHTML = "暂停";
	//     	ChangeK.setAttribute("data-run","0");
	//     	 marker.enableMassClear(); //设置后可以隐藏改点的覆盖物
	//          marker.hide();
	//     	lushu.start(function () {
   //              ChangeK.innerHTML = "开始";
   //              ChangeK.setAttribute("data-run","1");
   //          });
	//     }else if(runS == 0){
	//     	ChangeK.innerHTML = "开始";
	//     	ChangeK.setAttribute("data-run","1");
	//     	lushu.pause();
	//     }
   // };
    //---------添加地图类型控件-----------
    map.addControl(new BMap.MapTypeControl({
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ]}));

    // ---------定义缩放控件  -----------
    function ZoomControl() {
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
        this.defaultOffset = new BMap.Size(10, 100);
    }
    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMap.Control();

    // 自定义控件必须实现initialize方法，并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    ZoomControl.prototype.initialize = function (map) {
        //+-包裹层
        var mapwrap = document.createElement("div");
        mapwrap.className = 'zoomwrap';
        //创建一个放大img
        var plus_div = document.createElement("div");
        plus_div.className = 'plusDiv';
        var map_p_lus = document.createElement("p");
        map_p_lus.className = 'plus';
        var map_plus = document.createElement("img");
        map_plus.setAttribute("src", "asserts/resource/img/plus.png");

        //为img设置点击事件
        map_plus.onclick = function () {
            map.zoomTo(map.getZoom() + 2);
        }
        //创建一个缩小img
        var minus_div = document.createElement("div");
        minus_div.className = 'minusDiv';
        var map_m_inus = document.createElement("p");
        map_m_inus.className = 'minus';
        var img_minus = document.createElement("img");
        img_minus.setAttribute("src", "asserts/resource/img/minus.png");
        img_minus.onclick = function () {
            map.zoomTo(map.getZoom() - 2);
        }
        //添加放大的img图标到div中
        mapwrap.appendChild(plus_div);
        plus_div.appendChild(map_p_lus);
        map_p_lus.appendChild(map_plus);
        //添加缩小的img图标到div中
        mapwrap.appendChild(minus_div);
        minus_div.appendChild(map_m_inus);
        map_m_inus.appendChild(img_minus);
        //添加DOM元素到地图中
        map.getContainer().appendChild(mapwrap);
        //将DOM元素返回；
        return mapwrap;
    }

    // 创建控件实例
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);
</script>
</body>
</html>